package site.xuxingcan.NettyUtil;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * Created by xuxingcan on 16-7-25.
 */
public class JsonEncoder extends MessageToByteEncoder<String> {

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, String s, ByteBuf byteBuf) throws Exception {
        byte[] bytes;
        if (s == null || s.length() == 0) {
            bytes = "\n".getBytes("UTF-8");
        } else {
            if (!s.endsWith("\n")) {
                s += "\n";
            }
            bytes = s.getBytes("UTF-8");
        }
        byteBuf.writeBytes(bytes);
    }
}
